# -*- coding: utf-8 -*-

from django.db import models
#from django.contrib.sites.models import Site
from PIL import Image, ImageDraw

from settings import DEBUG, ALBUM_TYPES

# Create your models here.

class Album(models.Model):
    kind = models.CharField(max_length=4, choices=ALBUM_TYPES,
                            verbose_name=u'тип')
    name = models.CharField(max_length=30, verbose_name=u'название')
    cover = models.ImageField(upload_to='covers/',
                              verbose_name=u'обложка')
    class Meta:
        verbose_name = u'альбом'
        verbose_name_plural = u'альбомы'

    def show_cover(self):
        return '<img src="%s"  alt="%s" \
            title="%s"/>' % (self.cover.url, self.name, self.name)
    show_cover.allow_tags = True

    def __unicode__(self):
        return self.name

    def save(self, cov_size=(200, 150)):
        if not self.id and not self.cover:
            return

        super(Album, self).save()
        filename = str(self.cover.path)
        img = Image.open(filename)
        img.thumbnail(cov_size, resample=1)
        img.save(filename)

class Picture(models.Model):
    of_album = models.ForeignKey(Album)
    name = models.CharField(max_length=30, verbose_name=u'название')
    desc = models.CharField(max_length=150, verbose_name=u'описание')
    image = models.ImageField(upload_to='galleries/',
                              verbose_name=u'изображение')
    slideshow = models.BooleanField(default=False,
                                    verbose_name=u'в галерее')

    class Meta:
        verbose_name = u'картинка'
        verbose_name_plural = u'картинки'

    def __unicode__(self):
        return self.name

    def save(self, img_size=(800, 600)):
        if not self.id and not self.image:
            return

        super(Picture, self).save()
        filename = str(self.image.path)
        img = Image.open(filename)
        img.thumbnail(img_size, resample=1)
        img.save(filename)

        prev_size = [pix/4 for pix in img_size]
        img.thumbnail(prev_size, resample=1)
        draw = ImageDraw.Draw(img)
#        draw.rectangle((0, 0, prev_size[0]-2, prev_size[1]-2), outline=1)
        draw.line((0, 0, img.size[0], 0), width=3, fill=0)
        draw.line((img.size[0], 0, img.size[0], img.size[1]), width=3, fill=0)
        draw.line((img.size[0], img.size[1], 0, img.size[1]), width=4, fill=0)
        draw.line((0, img.size[1], 0, 0), width=3, fill=0)
        prev_filename = filename.replace('galleries/', 'galleries/preview_')
        img.save(prev_filename)

    def prev_filename(self):
        return self.image.name.replace('galleries/', 'galleries/preview_')
